package com.logic.landseaserver.task;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logic.system.service.IConfigurationService;
import com.logic.system.service.impl.ConfigurationService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.logic.landseaserver.common.LandeaConstants.SmsSendStatus;
import com.logic.landseaserver.common.config.SendMsgConfiguration;
import com.logic.landseaserver.common.util.SMSUtil;
import com.logic.landseaserver.domain.SendSmsRecord;
import com.logic.landseaserver.models.ddlock.DdingLockEvtService;
import com.logic.landseaserver.persistence.read.SendSmsRecordReadMapper;
import com.logic.landseaserver.persistence.write.SendSmsRecordWriteMapper;
import com.logic.landseaserver.service.IScheduleService;

/**
 * 
 *
 * 项目名称：system-server</br>
 * 类名称：CouponTask</br>
 * 类描述：定时发送短信</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年10月18日 下午4:01:23</br>
 * 
 * @version 1.0
 *
 */
@Component
public class SendSmsTask
{
    private static final Logger LOG = LoggerFactory.getLogger(SendSmsTask.class);
    
    @Autowired
    private IScheduleService iScheduleService;
    
    @Autowired
    private SendSmsRecordReadMapper sendSmsRecordReadMapper;
    
    @Autowired
    private SendSmsRecordWriteMapper sendSmsRecordWriteMapper;
    
    @Autowired
    private SendMsgConfiguration sendMsgConfiguration;
    
    @Autowired
    private DdingLockEvtService ddingLockEvtService;

    @Autowired
    private IConfigurationService configurationService;
    
    /**
     * 每隔2小时运行一次 扫描短信表中未发送成功的短信进行发送
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    // @Scheduled(cron = "0 1-59/3 * * * ?")
    public void sendSms()
    {
        try
        {
            LOG.info("sendSmsTask|定时任务开始......");
            boolean sendMsgFlag = iScheduleService.sendMsgFlag();
            if (sendMsgFlag)
            {
                LOG.info("sendSmsTask|发送短信定时任务开始......");
                
                // 删除7天前的短信记录,不管成功与失败
                Calendar currentDate = Calendar.getInstance();
                currentDate.add(Calendar.DATE, -7);
                
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("endTime", currentDate.getTime());
                //paramMap.put("status", SmsSendStatus.SEND_SUCCESS);
                sendSmsRecordWriteMapper.deleteSuccessSms(paramMap);
                LOG.info("sendSmsTask|删除7天前的短信记录完毕.");
                
                // 查询出未发送成功的短信进行发送(只查询昨天和今天的)
                Calendar queryDate = Calendar.getInstance();
                queryDate.add(Calendar.DATE, -1);
                queryDate.set(Calendar.HOUR_OF_DAY, 0);
                queryDate.set(Calendar.MINUTE, 0);
                queryDate.set(Calendar.SECOND, 0);
                paramMap.clear();
                paramMap.put("startTime", queryDate.getTime());
                paramMap.put("status", SmsSendStatus.SEND_SUCCESS);
                List<SendSmsRecord> needSendList = sendSmsRecordReadMapper.queryNeedSend(paramMap);
                if (CollectionUtils.isEmpty(needSendList))
                {
                    LOG.info("sendSmsTask|没有待发送的短信,等待下一次定时任务.");
                    return;
                }
                
                // 开始合并短信并且发送（目前只有门锁离线、电池电量过低预警）
                LOG.info("sendSmsTask|合并发送门锁离线短信开始.");
                ddingLockEvtService.mergeAndSend(needSendList, sendMsgConfiguration.getDoorLockOfflineCode());
                LOG.info("sendSmsTask|合并发送门锁电池预警短信开始.");
                ddingLockEvtService.mergeAndSend(needSendList, sendMsgConfiguration.getDoorLockbatteryLowCode());
                
                // 开始发送剩余短信
                send(needSendList);
            }
        }
        catch (Exception e)
        {
            LOG.error("sendSmsTask|发送短信时任务发生错误.", e);
        }
    }
    
    private void send(List<SendSmsRecord> needSendList)
    {
        for (SendSmsRecord sms : needSendList)
        {
            try
            {
                LOG.info("sendSmsTask|开始发送非合并短信=>" + sms.toString());
                String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
                boolean sendResult = SMSUtil.sendSms(sms.getSmsCode(), sms.getPhone(), sms.getContent(),signName);
                if (!sendResult)
                {
                    // 发送失败
                    LOG.error("sendSmsTask|发送短信失败.WID=" + sms.getWid());
                    // 更新状态
                    updateSmsRecord(sms.getId(), SmsSendStatus.SEND_FAILED);
                    continue;
                }
                
                LOG.info("sendSmsTask|发送成功.WID=" + sms.getWid());
                updateSmsRecord(sms.getId(), SmsSendStatus.SEND_SUCCESS);
            }
            catch (Exception e)
            {
                LOG.error("sendSmsTask|发送短信失败.WID=" + sms.getWid());
                updateSmsRecord(sms.getId(), SmsSendStatus.SEND_FAILED);
                continue;
            }
        }
    }
    
    private void updateSmsRecord(Integer id, Integer status)
    {
        try
        {
            SendSmsRecord update = new SendSmsRecord();
            update.setId(id);
            update.setStatus(status);
            update.setLastModifiedDtm(new Date());
            sendSmsRecordWriteMapper.updateByPrimaryKeySelective(update);
        }
        catch (Exception e)
        {
            LOG.error("sendSmsTask|更新短信记录失败.ID=" + id + ",status=" + status);
        }
    }
}